package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.swim.entity.Utente;
import org.swim.sessions.GestoreUtentiRemote;

/**
 * Servlet implementation class Registrazione
 */
public class Registrazione extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Registrazione() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		String idUtente = (String) session.getAttribute("idUtente");
		if(idUtente != null){
			request.getSession().removeAttribute("idUtente");
			
			response.setStatus(response.SC_MOVED_TEMPORARILY);
			response.setHeader("Location", "./");
			return;
		}

		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL,"localhost:1099"); 
		GestoreUtentiRemote gestore = null;
		try {
			InitialContext ctx = new InitialContext(env);
			gestore = (GestoreUtentiRemote)ctx.lookup("GestoreUtenti/remote");
			
		} catch (Exception e1){ 
			e1.printStackTrace();
		}
		String email = request.getParameter("email");
		Hashtable<String, Object> dati = new Hashtable<String, Object>();
		try{
			dati.put("email", email);
			dati.put("nome", request.getParameter("nome"));
			dati.put("cognome", request.getParameter("cognome"));
			dati.put("dataNascita", 
					(new SimpleDateFormat("yyyy-mm-dd")).parse(request.getParameter("dataNascita"))
			);
			dati.put("citta", request.getParameter("citta"));
			dati.put("password", request.getParameter("password"));
			Utente u = gestore.addUtente(dati);
			session.setAttribute("idUtente", u.getEmail());
			response.setContentType("text/html");
			response.getWriter().println("<h3>Registrazione completata con successo!</br><a href='./PaginaPersonale' >Vai alla tua pagina personale</a></h3>");
		} catch (Exception e){ 
			e.printStackTrace();
		}

	}

}
